import json
import re
import time

import execjs
import pymysql
import requests
import smtplib
from email.mime.text import MIMEText

def js_from_file(file_name):
    """
    读取js文件
    :return:
    """
    with open(file_name, 'r', encoding='UTF-8') as file:
        result = file.read()
    return result

class AccountChecker:
    def __init__(self):
        self.db = self.connect_database()
        self.cursor = self.db.cursor()
        self.wushuang=0
        self.rongyao=0
        self.xingyuan=0
        self.chuanshuo=0
        self.price=0
        self.pifuzongshu=0
        self.des=''
    def judgecondition(self, minwushuang,minrongyao,minxingyuan,minchuanshuo,maxprice,musthave,email,minpifuzongshu):
        if minwushuang> self.wushuang:
            return 0
        if minrongyao> self.rongyao:
            return 0
        if minxingyuan> self.xingyuan:
            return 0
        if minchuanshuo> self.chuanshuo:
            return 0
        if maxprice< self.price:
            return 0
        if minpifuzongshu> self.pifuzongshu:
            return 0
        for tmp in musthave:
            if tmp not in  self.des:
                return 0
        self.send_email(self.parse_description(origin=self.des), email, self.price)
        return 1
    @staticmethod
    def connect_database():
        try:
            return pymysql.connect(host='localhost', user='root', passwd='', port=3306,password='123456',db='panzhi')
        except Exception as e:
            print(f'Database connection failed: {e}')
            exit()

    @staticmethod
    def send_email(content, email, myprice):
        print('sending..')
        mail_host = 'smtp.163.com'
        mail_user = 'vjmbsd'
        mail_pass = 'HVYZEVNOSEOYSADS'
        sender = 'vjmbsd@163.com'
        receivers = [email] if email else ['2391860056@qq.com']

        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = f'{myprice}'
        message['From'] = sender
        message['To'] = ';'.join(receivers)

        try:
            smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
            # 登录到服务
            smtp.login(mail_user, mail_pass)
            # 发送
            smtp.sendmail(sender, receivers, message.as_string())
            # 退出
            smtp.quit()
            print('Email sent successfully')
        except smtplib.SMTPException as e:
            print(f'Error sending email: {e}')

    @staticmethod
    def parse_description(origin):
        pre = re.search('【订单编号】([\s\S]*?)【其他皮肤】', origin)
        return pre.group(1) if pre else ''

    def check_and_notify_users(self, account):
        try:
            with self.db.cursor() as cursor:
                sql = "SELECT * FROM users WHERE expiration_date >= CURDATE()"
                cursor.execute(sql)
                users = cursor.fetchall()
                for user in users:
                    if account['price'] <= user[2] and account['rongyao'] >= user[3] and account['xingyuan'] >= user[4] and account['wushuang'] >= user[5] and account['pifu'] >= user[6] and account['chuanshuo'] >=user[7] and user[9] in account['qufu']:
                        self.send_email(
                            f"Found a matching account: {account['description']}",
                            user[1],
                            account['price']
                        )

        except Exception as e:
            print(f"Error checking and notifying users: {e}")
    def getpanzhidata(self):
        url = "https://api.pzds.com/api/web-client/v2/public/goodsPublic/page"
        payload = '{"action":{"keywords":[],"merchantMark":null,"goodsCatalogueId":6,"gameId":7},"sort":null,"order":null,"page":1,"pageSize":100}'
        context1 = execjs.compile(js_from_file('test.js'))
        result1 = context1.call("myJiaMi", str(payload))
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate,  zstd',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Connection': 'keep-alive',
            'Content-Length': '136',
            'Channelinfo':'{"channelCode":null,"tag":null,"channelType":null,"searchWord":"null"}',
            'Content-Type': 'application/json;charset=UTF-8',
            'DNT': '1',
            'Host': 'api.pzds.com',
            'PZOs': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
            'PZPlatform': 'pc',
            'PZTimestamp': str(result1['Timestamp']),
            'PZVersion': '1.0.0',
            'PZVersionCode': '1',
            'Random': str(result1['Random']),
            'Sign': str(result1['strMd5']),
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
            'channelInfo': '{"channelCode":null,"tag":null,"channelType":null,"searchWord":"null"}',
        }
        headers1 = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Cookie': '_c_WBKFRo=pLkP4aKVyfZetYKbLfGZDB3BsrIdiIeXWqojb2nk; Hm_lvt_8e2c03f98f8af83cf09317d232baf903=1710312825,1710347948; pzfrom=null; bd_vid=null; qhclickid=null; uctrackid=null; keyword=null; Hm_lpvt_8e2c03f98f8af83cf09317d232baf903=1710481494',
            'DNT': '1',
            'Host': 'www.pzds.com',
            'Pragma': 'no-cache',
            'Referer': 'https://www.pzds.com/goodsList/7/6',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
            'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Microsoft Edge";v="122"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"'
        }
        try:
            response = requests.request('post',url,headers=headers,data=payload)
            mydict =    json.loads(response.text)
            a = mydict['data']['records']
            for tmp in a:
                bianhao = tmp['goodsNo']
                price=tmp['price']
                mysearch = "select * from wangzhezhanghao where bianhao='{bianhao}'".format(bianhao=bianhao)
                self.cursor.execute(mysearch)
                if not len(self.cursor.fetchall()):
                    #url = 'https://www.pzds.com/goodsDetails/' + bianhao + '/6'
                    self.des = tmp['title']
                    # res = re.search('【无双皮肤】([0-9]+)', self.des)
                    # wushuang = 0 if res is None else int(res.group(1))
                    # res = re.search('【传说皮肤】([0-9]+)', self.des)
                    # chuanshuo = 0 if res is None else int(res.group(1))
                    # res = re.search('【荣耀皮肤】([0-9]+)', self.des)
                    # rongyao = 0 if res is None else int(res.group(1))
                    # res = re.search('【星元皮肤】([0-9]+)', self.des)
                    # xingyuan = 0 if res is None else int(res.group(1))
                    # res = re.search('【皮肤数量】([0-9]+)', self.des)
                    # pifuzongshu = 0 if res is None else int(res.group(1))
                    res = re.search('无双皮肤([0-9]+)', self.des)
                    wushuang = 0 if res is None else int(res.group(1))
                    res = re.search('传说皮肤([0-9]+)', self.des)
                    chuanshuo = 0 if res is None else int(res.group(1))
                    res = re.search('荣耀典藏([0-9]+)', self.des)
                    rongyao = 0 if res is None else int(res.group(1))
                    res = re.search('星元皮肤([0-9]+)', self.des)
                    xingyuan = 0 if res is None else int(res.group(1))
                    res = re.findall('皮肤([0-9]+)', self.des)
                    pifuzongshu = 0 if res is None else int(res[len(res)-1])
                    account_info = {
                        'price': price,
                        'rongyao': rongyao,
                        'xingyuan': xingyuan,
                        'wushuang': wushuang,
                        'pifu': pifuzongshu,
                        'description': self.des,
                        'chuanshuo':chuanshuo,
                        'qufu':tmp['simpleMessage']
                    }
                    self.check_and_notify_users(account_info)
                    sql = "insert into wangzhezhanghao(bianhao,price,wushuang,rongyao,xingyuan,chuanshuo,pifu) values('{bianhao}',{price},{wushuang},{rongyao},{xingyuan},{chuanshuo},{pifu}) ".format(
                        bianhao=bianhao, price=price, wushuang=wushuang,rongyao=rongyao,xingyuan=xingyuan,chuanshuo=chuanshuo,pifu=pifuzongshu)
                    self.cursor.execute(sql)
                    self.db.commit()
        except  Exception as e:
            self.db.rollback()
            print('getpanzhidata:' + e.__str__())
    def getpangxiedata(self):
        url = "https://api.pxb7.com/api/product/list?game_id=13&rec=&category=%7B%221%22:0,%225%22:[],%2228%22:[],%2231%22:0,%2232%22:0,%2233%22:[],%2251%22:[],%2266%22:[],%2267%22:[],%2278%22:[],%2279%22:[],%2280%22:[],%2281%22:[],%2282%22:[],%2283%22:[],%2285%22:[],%2286%22:0,%2287%22:[],%2289%22:[]%7D&scope=%7B%22min_price%22:%22%22,%22max_price%22:%22%22,%22min_skin%22:%22%22,%22max_skin%22:%22%22,%22min_nobility_integral%22:%22%22,%22max_nobility_integral%22:%22%22,%22min_legend%22:%22%22,%22max_legend%22:%22%22,%22min_epic%22:%22%22,%22max_epic%22:%22%22,%22min_skin_value%22:%22%22,%22max_skin_value%22:%22%22%7D&services=all&sort=%7B%22type%22:%22isnew%22,%22method%22:2%7D&page=1&md5__1110=n40xn70QKCqeT405DIAwxmxWqImCD9AxRAOoD"
        payload = {
            "game_id": 13,
            "rec": "",
            "category": {"1":0,"5":[],"28":[],"31":0,"32":0,"33":[],"51":[],"66":[],"67":[],"78":[],"79":[],"80":[],"81":[],"82":[],"83":[],"85":[],"86":0,"87":[],"89":[]},
            "scope": {"min_price":"","max_price":"","min_skin":"","max_skin":"","min_nobility_integral":"","max_nobility_integral":"","min_legend":"","max_legend":"","min_epic":"","max_epic":"","min_skin_value":"","max_skin_value":""},
            "services": "all",
            "sort": {
                "type": "isnew",
                "method": 1
            },
            "page": 1
        }
        context2 = execjs.compile(js_from_file('pangxiejiami.js'))
        result2 = context2.call("pangxie", payload)
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'ApiToken': str(result2['ApiToken']),
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Host': 'api.pxb7.com',
            'LoginStatus': 'false',
            'Origin': 'https://www.pxb7.com',
            'Pragma': 'no-cache',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
            'RandomStr': str(result2['RandomStr']),
            'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'Sign': str(result2['Sign']),
            'Timestamp': str(result2['Timestamp']),
            'Token': str(result2['token']),
            'Cookie': 'sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22191b2e372094b1-0d8c1d7f7926fa8-4c657b58-3686400-191b2e3720abf9%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkxYjJlMzcyMDk0YjEtMGQ4YzFkN2Y3OTI2ZmE4LTRjNjU3YjU4LTM2ODY0MDAtMTkxYjJlMzcyMGFiZjkifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%7D; UM_distinctid=191b2e374574a3-035912d027db44-4c657b58-384000-191b2e374588d1; Hm_lvt_6d8ffc7e04e74b3866a454a4477796ce=1725283136,1725285558; Hm_lpvt_6d8ffc7e04e74b3866a454a4477796ce=1725285558; HMACCOUNT=33D0C8FEBB196485; aliyungf_tc=b987fe6c7e3f751d4539dd3fdd327e1fb16423d0b68ede404c1c69412c52da8d; acw_tc=3da7e834782ce66816bf9359e604ccc1314d342729631cce657ed7796b853321; acw_sc__v2=66d5c4c1a55585cfc3c5fef8bde026dfcf49a785; ssxmod_itna=iqRxRi0QDt0=G=G7DzODUDG28I2IxAKwP0RIN+oKfYD/+DvDnqD=GFDK40EoMhPQa0e4TEFG0mA4A57z=7GuYK8Y=xIP6C8LrpoDU4i8DCdxvETDemtD5xGoDPxDeDAAqGaDb4DrgTqGPg0wNVmw=D3qDwDB=DmqG2tWtDm4DfDDdgQDwIfqqD0qqr2Y+ewY4DbrUZ4L2qseDSb7XTpqDMD7tD/4e12itDGkyz2Y0ZIZWWkh6PHeGuDG=oukj56AUxMd=WL7GFQ7Go48moDgpe+7x4+3h54yGeYAAxQdxpQDz4+D1N4++GDYDG34m84diP4D; ssxmod_itna2=iqRxRi0QDt0=G=G7DzODUDG28I2IxAKwP0RIN+oIYG97T4xBuAOD7PXAYkwmYm7D8OHqkq0eqqNk0+6TgGets7dYYIYMa=x9OWypDoAXWZPkirN1aHQhnP9Y0QbQB6rKgSauKUxKoQaEF72l07a=Gq9j04YPWwlG2zn=mxMe2qyBIiKlGCrCmrGYWeeAmb=Pe4khuq=BWrqx5hwY7O+OGGygW423yIFzuiu=qKChfxToHipoaexKeHoQ3xMe=TqDLGliBNkyMOFLqTos0FgUOqHPnDpp6ekhot7nGWxaZ+VS7zs=thfS65Qd3OoncK3gh9GUZpGN1dbc0fQLZhx2ENhGXAxK3EUfjfVOGC1=ijDb2w1OorcpxmLxj2O0pYAeGiphlLrO6rCqcPwchomaAfiGsgQLPK+pvBnPqAmmRvCgWSYNObQ=OqxRELbjGWe6jEh0pibthDvd8PIjaUjvm2t6/XkQ2jtL5BekAe4WRcZ07rau0PI=FL69mBrklxSz=A7XLGfrcFnh7Ecpu+tMPuosPng7Kuq4YeVGOMRe5TPWrE84OhlydowhEeqpaE67kj5eTp54BR0FBQoRSF98cxm=ahqwlfhhtNswI+x4ltrUiFDG2DrqlGTWRo348WbcX/BnU2XLvESY/+u=+E33NF0ghkoEfgeYOCGT9hlkXhuKad0vSuv8GPDXjXnuV3DCYNDGcDD20qo0b+hErDD=',
            'Visitorid': 'eca9ab7e-1d4b-47ac-b347-3111a22f8cce'
        }
        try:
            response = requests.request("GET", url, headers=headers, data=payload)
            mydict = json.loads(response.text)
            a = mydict['data']['list']
            for tmp in a:
                self.des=tmp['name']
                prebianhao=re.search('^([A-Z|0-9]+)',self.des)
                if prebianhao is None:
                    continue
                bianhao=prebianhao.group(1)
                mysearch = "select * from wangzhezhanghao where bianhao='{bianhao}'".format(bianhao=bianhao)
                self.cursor.execute(mysearch)
                if  not len(self.cursor.fetchall()):
                    price=int(tmp['price'])
                    res = re.search('【无双皮肤([0-9]+)】', self.des)
                    wushuang = 0 if res is None else int(res.group(1))
                    res = re.search('【传说皮肤([0-9]+)】', self.des)
                    chuanshuo = 0 if res is None else int(res.group(1))
                    res = re.search('【荣耀典藏([0-9]+)】', self.des)
                    rongyao = 0 if res is None else int(res.group(1))
                    res = re.search('【星元皮肤([0-9]+)】', self.des)
                    xingyuan = 0 if res is None else int(res.group(1))
                    res = re.search(' 皮肤([0-9]+) 贵族', self.des)
                    pifuzongshu = 0 if res is None else int(res.group(1))
                    account_info = {
                        'price': price,
                        'rongyao': rongyao,
                        'xingyuan': xingyuan,
                        'wushuang': wushuang,
                        'chuanshuo':chuanshuo,
                        'pifu': pifuzongshu,
                        'description': self.des  # 从爬虫获取的账号描述
                    }
                    self.check_and_notify_users(account_info)
                    sql = "insert into wangzhezhanghao(bianhao,price,wushuang,rongyao,xingyuan,chuanshuo,pifu) values('{bianhao}',{price},{wushuang},{rongyao},{xingyuan},{chuanshuo},{pifu}) ".format(
                        bianhao=bianhao, price=price, wushuang=wushuang, rongyao=rongyao, xingyuan=xingyuan, chuanshuo=chuanshuo, pifu=pifuzongshu)
                    self.cursor.execute(sql)
                    self.db.commit()
        except  Exception as e:
            self.db.rollback()
            print('getpangxiedata:' + e.__str__())
    def clean_expired_users(self):
        try:
            with self.db.cursor() as cursor:
                sql = "DELETE FROM users WHERE expiration_date < CURDATE()"
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print(f"Error cleaning expired users: {e}")
            self.db.rollback()
if __name__ == '__main__':
    account_checker = AccountChecker()
    while True:
        print(1)
        account_checker.clean_expired_users()
        account_checker.getpanzhidata()
        #account_checker.getpangxiedata()
        time.sleep(60)
